// components/dynamic-form/index.js
const { FormUtils } = require('../../utils/form-config.js');

Component({
  properties: {
    // 表单类型
    formType: {
      type: String,
      value: ''
    },
    // 表单数据
    formData: {
      type: Object,
      value: {}
    },
    // 是否显示错误
    showErrors: {
      type: Boolean,
      value: true
    }
  },

  data: {
    fields: [],
    errors: {}
  },

  observers: {
    'formType': function(formType) {
      if (formType) {
        this.initForm();
      }
    }
  },

  methods: {
    // 初始化表单
    initForm() {
      const config = FormUtils.getFormConfig(this.data.formType);
      if (config) {
        this.setData({
          fields: config.fields
        });
      }
    },

    // 输入框输入事件
    onFieldInput(e) {
      const { key } = e.currentTarget.dataset;
      const value = e.detail.value;
      
      this.updateFormData(key, value);
      this.validateField(key, value);
    },

    // 选择器变化事件
    onPickerChange(e) {
      const { key } = e.currentTarget.dataset;
      const index = e.detail.value;
      const field = this.data.fields.find(f => f.key === key);
      
      if (field && field.options) {
        const value = field.options[index].value;
        this.updateFormData(key, value);
        this.validateField(key, value);
      }
    },

    // 开关变化事件
    onSwitchChange(e) {
      const { key } = e.currentTarget.dataset;
      const value = e.detail.value;
      
      this.updateFormData(key, value);
      this.validateField(key, value);
    },

    // 数组项输入事件
    onArrayItemInput(e) {
      const { key, index } = e.currentTarget.dataset;
      const value = e.detail.value;
      
      const formData = { ...this.data.formData };
      formData[key][index] = value;
      
      this.setData({ formData });
      this.validateField(key, formData[key]);
    },

    // 添加数组项
    onAddArrayItem(e) {
      const { key } = e.currentTarget.dataset;
      const field = this.data.fields.find(f => f.key === key);
      
      const formData = { ...this.data.formData };
      if (!formData[key]) {
        formData[key] = [];
      }
      formData[key].push(FormUtils.getDefaultValue(field));
      
      this.setData({ formData });
      this.validateField(key, formData[key]);
    },

    // 删除数组项
    onRemoveArrayItem(e) {
      const { key, index } = e.currentTarget.dataset;
      
      const formData = { ...this.data.formData };
      formData[key].splice(index, 1);
      
      this.setData({ formData });
      this.validateField(key, formData[key]);
    },

    // 对象字段输入事件
    onObjectFieldInput(e) {
      const { parentKey, key } = e.currentTarget.dataset;
      const value = e.detail.value;
      
      const formData = { ...this.data.formData };
      if (!formData[parentKey]) {
        formData[parentKey] = {};
      }
      formData[parentKey][key] = value;
      
      this.setData({ formData });
      this.validateField(parentKey, formData[parentKey]);
    },

    // 更新表单数据
    updateFormData(key, value) {
      const formData = { ...this.data.formData };
      formData[key] = value;
      
      // 计算计算字段
      const calculatedData = FormUtils.calculateFields(this.data.formType, formData);
      
      this.setData({ formData: calculatedData });
      
      // 触发数据变化事件
      this.triggerEvent('formchange', {
        formData: calculatedData,
        changedField: key,
        changedValue: value
      });
    },

    // 验证单个字段
    validateField(key, value) {
      const field = this.data.fields.find(f => f.key === key);
      if (!field) return;

      const errors = FormUtils.validateField(field, value);
      
      this.setData({
        [`errors.${key}`]: errors
      });

      // 触发验证事件
      this.triggerEvent('fieldvalidate', {
        field: key,
        errors: errors,
        isValid: errors.length === 0
      });
    },

    // 验证整个表单
    validateForm() {
      const { isValid, errors } = FormUtils.validateForm(this.data.formType, this.data.formData);
      
      this.setData({ errors });
      
      this.triggerEvent('formvalidate', {
        isValid,
        errors,
        formData: this.data.formData
      });
      
      return { isValid, errors };
    },

    // 获取表单数据
    getFormData() {
      return this.data.formData;
    },

    // 设置表单数据
    setFormData(formData) {
      this.setData({ formData });
    },

    // 重置表单
    resetForm() {
      const formData = FormUtils.initFormData(this.data.formType);
      this.setData({ 
        formData,
        errors: {}
      });
    },

    // 获取选择器索引
    getPickerIndex(field) {
      const value = this.data.formData[field.key];
      if (!field.options) return 0;
      
      const index = field.options.findIndex(option => option.value === value);
      return index >= 0 ? index : 0;
    },

    // 获取选择器文本
    getPickerText(field) {
      const value = this.data.formData[field.key];
      if (!field.options) return field.placeholder || '请选择';
      
      const option = field.options.find(option => option.value === value);
      return option ? option.label : (field.placeholder || '请选择');
    }
  }
});
